<?php
namespace Admin\Frontend\Controllers;

use Admin\Models\crm\XhcustInfo;
use Helpers\Area;
use Helpers\Cache;
use Helpers\Hrm;
use Helpers\Main;
use Helpers\Assets;
use Helpers\Template;
use Helpers\Tool;
use Helpers\User;
use Helpers\UserPower;
use Helpers\HttpClient;
use Helpers\XhException;
use Modules\Power;
use Modules\School;
use Phalcon\Db\Adapter\Pdo\Mysql;
use Admin\Models\user\XhsysUser;
use Admin\Models\sys\XhsysEnum;
use Admin\Models\sys\XhsysConfig;
use Admin\Models\sys\XhsysUserTch;
use Admin\Models\school\XhschoolInfo;
use Admin\Models\stats\XhstatsBrushgroup;
use Admin\Models\stats\XhstatsBrushgroupuser;
use Services\BigData;
use Services\CloudTask;
use Services\ResBase;

class StatsschoolController extends ControllerBase
{

    public static $status = [1 => '待审批' , 2 => '审批通过' , 3 =>'审批不通过'];
    /**
     * 根据类型获取习题库枚举
     *
     * @param $type
     * @return array
     * @throws \Exception
     *
     * create by ck 20180325
     * modify by ck 20180712
     */
//    private function getQuestionBaseEnum($type)
//    {
//        return ResBase::getDictionaries($type);
////        static $enumData = false;
////        if ($enumData === false) {
////            $httpClient = new HttpClient(Main::getConfigByName('resServerInterface')['questionBaseUrl']);
////            $response   = $httpClient->get('/api/v1/dictionaries');
////            if (!$response->isSuccess()) {
////                throw new \Exception('学科年级获取失败');
////            }
////            $enumData = $response->toArray();
////        }
////        $targetEnum = [];
////        foreach ($enumData as $row) {
////            if ($row['paramType'] == $type && $row['status'] == 1) {
////                $targetEnum[$row['id']] = $row['name'];
////            }
////        }
////        return $targetEnum;
//    }

    /**
     * 学校教辅使用情况
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20171031
     * modify by ck 20180325    添加学科及年级下拉框
     */
//    public function bookTchAction()
//    {
//        $this->view->pick('statsschool/bookTch');
//        Assets::sweetAlert2();
//        Assets::select2('js/statsschool/bookTch.js');
////        return true;
////        $schoolArr = UserPower::getAuthorizationSchool(true);
////        if ($schoolArr === false) {
////            return $this->sendViewError('无学校查看权限');
////        }
////        else if ($schoolArr === true) {
////            $schoolArr = XhschoolInfo::getSchoolSupportArray();
////        }
//        try {
//            return $this->view->setVars([
////                'viewAll'   => User::allSchoolPower(),
//                'viewAll'   => School::getPower() === true,
//                'schoolArr' => User::getSchool(true),
//                'subjectArr'=> ResBase::getDictionaries('subject'),
//                'gradeArr'  => ResBase::getDictionaries('grade'),
//            ]);
//        }
//        catch (\Exception $e) {
//            return $this->sendViewError($e->getMessage());
//        }
//    }
//
//    /**
//     * 开始数据缓存
//     *
//     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
//     *
//     * create by ck 20171228
//     */
//    public function startBookTchCacheAction()
//    {
//        set_time_limit(0);
//        ignore_user_abort(true);
//        $schoolId   = $this->request->getPost('schoolId', 'int');
//        $startTime  = $this->request->getPost('startTime', 'string');
//        $endTime    = $this->request->getPost('endTime', 'string');
//        $subjectId  = $this->request->getPost('subjectId', 'int');
//        $gradeId    = $this->request->getPost('gradeId', 'int');
//        $startTime  = strtotime($startTime);
//        $endTime    = strtotime($endTime);
//        if (!$schoolId || !$startTime || !$endTime) {
//            return $this->sendErrorResponse(400, '缺少必要参数');
//        }
//        if ($startTime > time()) {
//            return $this->sendErrorResponse(400, '日期超出限制，不可查询');
//        }
//        if (($endTime - $startTime) > 3600 * 24 * 31){
//            return $this->sendErrorResponse(400, '最多查询一个月数据');
//        }
//        $cacheKey = "book_tch_{$subjectId}_{$gradeId}_{$schoolId}_{$startTime}_{$endTime}";
//        if (Cache::exists($cacheKey)) {
//            return $this->sendSuccessResponse('缓存已存在，可直接使用');
//        }
//        try {
//            $bookUsage = $this->getBookTchUsage($schoolId, $startTime, $endTime, $subjectId, $gradeId);
//            if (!Cache::save($cacheKey, $bookUsage, 3600 * 12)) {
//                return $this->sendErrorResponse(500, '缓存保存失败');
//            }
//            return $this->sendSuccessResponse('缓存成功，可查询');
//        }
//        catch (\Exception $e) {
//            Cache::save($cacheKey, '缓存失败：' . $e->getMessage(), 3600);
//            return $this->sendErrorResponse(500, $e->getMessage());
//        }
//
//    }
//
//    /**
//     * 检查缓存是否存在
//     *
//     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
//     *
//     * create by ck 20171228
//     */
//    public function checkBookTchCacheAction()
//    {
//        $schoolId   = $this->request->getPost('schoolId', 'int');
//        $startTime  = $this->request->getPost('startTime', 'string');
//        $endTime    = $this->request->getPost('endTime', 'string');
//        $subjectId  = $this->request->getPost('subjectId', 'int');
//        $gradeId    = $this->request->getPost('gradeId', 'int');
//        $startTime  = strtotime($startTime);
//        $endTime    = strtotime($endTime);
//        if (!$schoolId || !$startTime || !$endTime) {
//            return $this->sendErrorResponse(400, '缺少必要参数', null, false);
//        }
//        $cacheKey = "book_tch_{$subjectId}_{$gradeId}_{$schoolId}_{$startTime}_{$endTime}";
//        if (!Cache::exists($cacheKey)) {
//            return $this->sendErrorResponse(500, '缓存未生成', null, false);
//        }
//        return $this->sendSuccessResponse('缓存存在，可查询');
//    }
//
//    /**
//     * 获取教辅使用情况
//     *
//     * @return \Phalcon\Mvc\View|string
//     *
//     * create by ck 20171031
//     * modify by ck 20171204    添加反转查看
//     */
//    public function bookTchFixAction()
//    {
//        $this->view->pick('statsschool/bookTchFix');
//        $schoolId       = $this->request->getQuery('schoolId', 'int');
//        $startTime      = $this->request->getQuery('startTime', 'string');
//        $endTime        = $this->request->getQuery('endTime', 'string');
//        $subjectId      = $this->request->getQuery('subjectId', 'int');
//        $gradeId        = $this->request->getQuery('gradeId', 'int');
//        $reverse        = $this->request->getQuery('reverse', 'string') == 'true' ? true : false;
//        $startTime      = strtotime($startTime);
//        $endTime        = strtotime($endTime);
//        if (!$schoolId || !$startTime || !$endTime) {
//            return $this->sendViewError('缺少必要参数');
//        }
//        if ($startTime > time()) {
//            return $this->sendViewError('日期超出限制，不可查询');
//        }
//        if (($endTime - $startTime) > 3600 * 24 * 31){
//            return $this->sendViewError('最多查询一个月数据');
//        }
//        try {
//            $cacheKey = "book_tch_{$subjectId}_{$gradeId}_{$schoolId}_{$startTime}_{$endTime}";
//            if (Cache::exists($cacheKey)) {
//                $bookUsage = Cache::get($cacheKey);
//                if (is_string($bookUsage)) {
//                    Cache::delete($cacheKey);
//                    return $this->sendViewError($bookUsage);
//                }
//            }
//            else {
//                $bookUsage = $this->getBookTchUsage($schoolId, $startTime, $endTime, $subjectId, $gradeId);
//            }
//            //逆转
//            $tchUsage = [];
//            if ($reverse) {
//                foreach ($bookUsage as $book) {
//                    foreach ($book['userWorkTimes'] as $workTime) {
//                        if (!isset($tchUsage[$workTime['teacherId']])) {
//                            $tchUsage[$workTime['teacherId']] = [
//                                'teacherId'     => $workTime['teacherId'],
//                                'teacherName'   => $workTime['teacherName']
//                            ];
//                        }
//                        $tchUsage[$workTime['teacherId']]['bookWorkTimes'][] = [
//                            'workTimes'         => $workTime['workTimes'],
//                            'topicCount'        => $workTime['topicCount'],
//                            'topicRepeatCount'  => $workTime['topicRepeatCount'],
//                            'bookId'            => $book['bookId'],
//                            'bookName'          => $book['bookName'],
//                        ];
//                    }
//                }
//            }
//            return $this->view->setVars([
//                'reverse'       => $reverse,
//                'bookUsage'     => $reverse ? $tchUsage : $bookUsage,
//                'schoolName'    => XhschoolInfo::getSchoolSupportArray()[$schoolId]
//            ]);
//        }
//        catch (\Exception $e) {
//            return $this->sendViewError($e->getMessage());
//        }
//    }
//
//    /**
//     * 获取书本使用情况
//     *
//     * @param $schoolId
//     * @param $startTime
//     * @param $endTime
//     * @param $subjectId
//     * @param $gradeId
//     * @return array
//     * @throws \Exception
//     *
//     * create by ck 20171031
//     * modify by ck 20180325    添加年级及科目筛选
//     */
//    private function getBookTchUsage($schoolId, $startTime, $endTime, $subjectId, $gradeId)
//    {
//        //新题库
//        $configName = 'CA103001-3';
//        $url = Main::getConfigByName('stats_' . $configName)['url'];
//        if (!$url) {
//            throw new \Exception($configName . '配置地址不存在！');
//        }
//        $httpClient = new HttpClient($url);
//        $response = $httpClient->setTimeout(60 * 5)->get('/intranet/work/statistic/school/books', [
//            'schoolId'  => $schoolId,
//            'startTime' => $startTime,
//            'endTime'   => $endTime,
//            'subject'   => intval($subjectId),
//            'period'    => intval($gradeId)
//        ]);
//        if (!$response->isSuccess()) {
//            throw new \Exception($configName . '请求失败：' . json_encode($response, JSON_UNESCAPED_UNICODE));
//        }
//        $bookUsage = $response->toArray();
//        if ($bookUsage === false) {
//            throw new \Exception($configName . '请求失败：返回不正确：' . $response->body);
//        }
//
//        return $bookUsage;
//        //2.0题库
////        $bookUsage2 = $this->getCloudTaskBookUsage2($schoolId, $startTime, $endTime);
//
////        return array_merge($bookUsage, $bookUsage2);
//    }
//
//    /**
//     * 获取云作业2书本使用情况
//     *
//     * @param $schoolId
//     * @param $startTime
//     * @param $endTime
//     * @return array
//     * @throws \Exception
//     *
//     * create by ck 20171031
//     */
//    private function getCloudTaskBookUsage2($schoolId, $startTime, $endTime)
//    {
//        $bookUsage  = [];
//        $dbName     = '';
//        $startTime  = date('Y-m-d H:i:s', $startTime);
//        $endTime    = date('Y-m-d H:i:s', $endTime);
//        $conn       = Main::getSchoolMainDB($schoolId, $dbName);
//        if (!$conn) {
//            throw new \Exception('数据库连接失败');
//        }
//        $bookUserList = $conn->fetchAll('SELECT tk_tr_id as examId, tr_name as examName, tk_us_id as tchId, us_name as tchName FROM tk_power, tree_homework_list, users WHERE tk_tr_id = tr_id AND tk_us_id = us_id AND us_flag = 4 AND us_xk_flag = 0 ORDER BY tk_tr_id');
//        $bookNameList = array_column($bookUserList, 'examName', 'examId');
//        $userNameList = array_column($bookUserList, 'tchName', 'tchId');
//
//        //获取老师对应题库id
//        $tchBooks = [];
//        foreach ($bookUserList as $row) {
//            $tchBooks[$row['tchId']][] = $row['examId'];
//        }
//        foreach ($tchBooks as $tchId => $examIds) {
//            $tchBooks[$tchId] = [];
//            foreach ($examIds as $examId) {
//                $tchBooks[$tchId][$examId] = [
//                    'workTimes'         => 0,
//                    'topicCount'        => 0,
//                    'topicRepeatCount'  => 0
//                ];
//            }
//            $examIds  = implode(',', $examIds);
//            $collList = $conn->fetchAll("SELECT co_id,te_us_id FROM attendclass_time_class, teacher_list, course_list, class_list, system_type, users WHERE cl_at_id = at_id AND co_id = te_co_id AND te_us_id = us_id AND us_xk_flag = 0 AND te_flag = 0 AND cl_flag = 1 AND cl_id = te_cl_id AND co_coach_flag = 0 AND co_typeflag = 1 AND co_km_id = sy_id AND te_us_id = {$tchId} AND at_qc_id IN ( SELECT sy_id FROM system_type WHERE sy_type = 'kkqcsz' AND sy_state = 0 AND sy_name2 = 1 ) GROUP BY co_id, cl_id ORDER BY co_ord");
//            foreach ($collList as $record) {
//                $dbCourse   = $dbName . '_course' . $record['co_id'];
////                $examFixNum = $conn->fetchAll("SELECT count(DISTINCT(lh_le_id)) as workTimes,ho_tr_id as examId FROM {$dbCourse}.homework_list_base,{$dbCourse}.lesson_homework_list,{$dbCourse}.lesson_course where ho_id = lh_ho_id AND le_id = lh_le_id and le_tmpflag = 0 AND le_us_id = {$tchId} AND ho_tr_id in ({$examIds}) AND le_dates >= '{$startTime}' AND le_dates < '{$endTime}' GROUP BY ho_tr_id");
//                $examFixNum = $conn->fetchAll("SELECT ho_tr_id as examId,count(DISTINCT(lh_le_id)) as workTimes,count(ho_sys_ho_id) as topicRepeatCount,count(DISTINCT(ho_sys_ho_id)) as topicCount FROM {$dbCourse}.homework_list_base,{$dbCourse}.lesson_homework_list,{$dbCourse}.lesson_course where ho_id = lh_ho_id AND le_id = lh_le_id and le_tmpflag = 0 AND le_us_id = {$tchId} AND ho_tr_id in ({$examIds}) AND le_dates >= '{$startTime}' AND le_dates < '{$endTime}' AND ho_parent_id = 0 GROUP BY ho_tr_id");
//                foreach ($examFixNum as $row) {
////                    @$tchBooks[$tchId][$row['examId']] += $row['workTimes'];
//                    $tchBooks[$tchId][$row['examId']]['workTimes']         += $row['workTimes'];
//                    $tchBooks[$tchId][$row['examId']]['topicCount']        += $row['topicCount'];
//                    $tchBooks[$tchId][$row['examId']]['topicRepeatCount']  += $row['topicRepeatCount'];
//                }
//            }
//        }
//        foreach ($tchBooks as $tchId => $examFix) {
//            foreach ($examFix as $examId => $info) {
//                if (!isset($bookUsage[$examId])) {
//                    $bookUsage[$examId] = ['bookId' => $examId, 'bookName' => $bookNameList[$examId], 'userWorkTimes' => []];
//                }
////                $bookUsage[$examId]['userWorkTimes'][] = ['teacherId' => $tchId, 'teacherName' => $userNameList[$tchId], 'workTimes' => $info['workTimes']];
//                $bookUsage[$examId]['userWorkTimes'][] = ['teacherId' => $tchId, 'teacherName' => $userNameList[$tchId]] + $info;
//            }
//        }
//        return array_values($bookUsage);
//    }

    /**
     * 学校教师应用使用情况
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20171031
     */
    public function tchAppAction()
    {
        $this->view->pick('statsschool/tchApp');
        Assets::select2('js/statsschool/tchApp.js');
        return $this->view->setVars([
            'grade'     => XhsysEnum::getEnumByNodeName('年级'),
            'subject'   => XhsysEnum::getEnumByNodeName('学科'),
            'viewAll'   => School::getPower() === true,
            'schoolArr' => User::getSchool(true)
        ]);
//        return true;
//        $schoolArr = UserPower::getAuthorizationSchool(true);
//        if ($schoolArr === false) {
//            return $this->sendViewError('无学校查看权限');
//        }
//        else if ($schoolArr === true) {
//            $schoolArr = XhschoolInfo::getSchoolSupportArray();
//        }
//        return $this->view->setVars([
//            'schoolArr' => $schoolArr
//        ]);
    }

    /**
     * 教师应用使用情况页面
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20171103
     * modify by ck 20180109
     */
    public function tchAppFixAction()
    {
        $this->view->pick('statsschool/tchAppFix');
        $schoolId       = $this->request->getQuery('schoolId', 'int');
        $startTime      = $this->request->getQuery('startTime', 'string');
        $endTime        = $this->request->getQuery('endTime', 'string');
        $grade          = $this->request->getQuery('grade', 'int');
        $subject        = $this->request->getQuery('subject', 'int');
//        $startTime      = strtotime($startTime);
//        $endTime        = strtotime($endTime);
        if (!$schoolId || !$startTime || !$endTime) {
            return $this->sendViewError('缺少必要参数');
        }
        if (strtotime($startTime) > time()) {
            return $this->sendViewError('日期超出限制，不可查询');
        }
        if ((strtotime($endTime) - strtotime($startTime)) > 3600 * 24 * 31){
            return $this->sendViewError('最多查询一个月数据');
        }
        try {
            $appUsage = $this->getTchAppUsage($schoolId, $startTime, $endTime, ['grade' => $grade, 'subject' => $subject]);
            //组合教师学科，年级，熟练度
//            $tchIds = array_column($appUsage, 'tchId');
//            if ($tchIds) {
//                $tchInfo = XhsysUserTch::find([
//                    'columns'    => 'iUserId,iSubject,iCurGrade,iProficiency,sAdminClass,sEBagClass,sDuty',
//                    'conditions' => 'bDelete = 0 AND iUserId IN ({idArr:array})',
//                    'bind'       => ['idArr' => $tchIds]
//                ])->toArray();
//                Tool::runEnum($tchInfo, [
//                    'iSubject'      => XhsysEnum::getEnumByNodeName('学科'),
//                    'iCurGrade'     => XhsysEnum::getEnumByNodeName('年级'),
//                    'iProficiency'  => XhsysEnum::getEnumByNodeName('熟练程度')
//                ]);
//                $appUsage = array_column($appUsage, null, 'tchId');
//                foreach ($tchInfo as $tch) {
//                    if (isset($appUsage[$tch['iUserId']])) {
//                        $appUsage[$tch['iUserId']]['subject']       = $tch['iSubject'];
//                        $appUsage[$tch['iUserId']]['grade']         = $tch['iCurGrade'];
//                        $appUsage[$tch['iUserId']]['proficiency']   = $tch['iProficiency'];
//                        $appUsage[$tch['iUserId']]['adClass']       = $tch['sAdminClass'];
//                        $appUsage[$tch['iUserId']]['eBagClass']     = $tch['sEBagClass'];
//                        $appUsage[$tch['iUserId']]['duty']          = $tch['sDuty'];
//                    }
//                }
//                $appUsage = array_values($appUsage);
//            }
            return $this->view->setVars([
                'appUsage'      => $appUsage,
                'schoolName'    => XhschoolInfo::getSchoolSupportArray()[$schoolId]
            ]);
        }
        catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
     * 获取教师应用使用情况
     *
     * @param $schoolId
     * @param $startTime
     * @param $endTime
     * @param $extraParams
     * @return array
     * @throws \Exception
     *
     * create by ck 20171103
     * modify by ck 20180109    可筛选，并直接组装信息
     */
    public function getTchAppUsage($schoolId, $startTime, $endTime, $extraParams = [])
    {
        //获取教师列表
        $conditions = '';
        if (isset($extraParams['grade']) && $extraParams['grade']) {
            $conditions .= " AND B.iCurGrade = '{$extraParams['grade']}'";
        }
        if (isset($extraParams['subject']) && $extraParams['subject']) {
            $conditions .= " AND B.iSubject = '{$extraParams['subject']}'";
        }
        if(isset($extraParams['userId']) && $extraParams['userId']){
            $conditions .= " AND A.iUserId = '{$extraParams['userId']}'";
        }
        $sql = "select A.iUserId as tchId, A.sUserName as tchName, B.iSubject as `subject`, B.iCurGrade as grade,B.iProficiency as proficiency, B.sAdminClass as adClass,B.sEBagClass as eBagClass, B.sDuty as duty 
                from XHSys_User A LEFT JOIN XHSys_UserTch B ON A.iUserId = B.iUserId
                WHERE A.bDelete = 0 AND A.bHistory = 0 AND A.iUserType = 4 AND A.iSchoolId = '{$schoolId}' AND IFNULL(B.bDelete, 0) = 0 {$conditions}";
        $tchList = $this->db->fetchAll($sql);
        Tool::runEnum($tchList, [
            'subject'       => XhsysEnum::getEnumByNodeName('学科'),
            'grade'         => XhsysEnum::getEnumByNodeName('年级'),
            'proficiency'   => XhsysEnum::getEnumByNodeName('熟练程度')
        ]);
        $tchList = array_column($tchList, null, 'tchId');
//        $parameters = [
//            'columns'    => 'iUserId,sUserName',
//            'conditions' => 'bDelete = 0 AND bDisable = 0 AND bCompany = 0 AND bHistory = 0 AND iSchoolId = :schoolId: AND iUserType = 4',
//            'bind'       => ['schoolId' => $schoolId]
//        ];
//        $tchList = XhsysUser::find($parameters)->toArray();
//        $tchList = array_column($tchList, 'sUserName', 'iUserId');

        //获取3.0应用列表
        $url = Main::getConfigByName('jAppServer')['url'];
        if (!$url) {
            throw new \Exception('应用服务配置不存在');
        }
        $httpClient = new HttpClient($url);
//        $response   = $httpClient->postJson('/api/v1/users/installed/apps', ['userIds' => array_keys($tchList)]);
        $response   = $httpClient->postJson('/api/v1/users/assigned/apps', ['userIds' => array_keys($tchList)]);
        if (!$response->isSuccess()) {
            throw new \Exception('获取列表失败：' . json_encode($response, JSON_UNESCAPED_UNICODE));
        }
        $tchAppList = $response->toArray();

        //处理需统计应用及教师列表
        $appCodeList = $this->getStatsAppInfo();
        $appTchList  = [];
        foreach ($tchAppList as $tchApp) {
            foreach ($tchApp['installedApps'] as $app) {
                if (key_exists($app['appCode'], $appCodeList)) {
                    $appTchList[$app['appCode']][] = $tchApp['userId'];
                }
            }
        }

        //获取各应用使用情况
        $appTchUsage = [];
        foreach ($appTchList as $appCode => $tchIds) {
            try {
                $appTchUsage[$appCode] = $this->getAppUsageInfo($appCode, $tchIds, $startTime, $endTime, $schoolId);
            }
            catch (\Exception $e) {
                continue;
            }
        }
        //合并云作业数据
        if (array_key_exists('CA103001', $appTchUsage)) {
            $cloudTask3 = $this->getAppUsageInfo('CA103001-3', $appTchList['CA103001'], $startTime, $endTime, $schoolId);
            $cloudTask2 = array_column($appTchUsage['CA103001'], null, 'tchId');
            foreach ($cloudTask3 as $row) {
                $tchId = $row['tchId'];
                if (!isset($cloudTask2[$tchId])) {
                    $cloudTask2[$tchId] = $row;
                    continue;
                }
                $cloudTask2[$tchId]['taskFixNum']   += $row['taskFixNum'];
                $cloudTask2[$tchId]['taskTopicNum'] += $row['taskTopicNum'];
                $cloudTask2[$tchId]['practiceNum']  += $row['practiceNum'];
                $row['lastFixTime'] > $cloudTask2[$tchId]['lastFixTime'] and $cloudTask2[$tchId]['lastFixTime'] = $row['lastFixTime'];
            }
            $appTchUsage['CA103001'] = array_values($cloudTask2);
        }

        //组合教师应用使用情况
        $tchAppUsage = [];
        foreach ($appTchUsage as $appCode => $usage) {
            foreach ($usage as $row) {
                $tchId = $row['tchId'];
                if (!isset($tchAppUsage[$tchId])) {
                    $tchAppUsage[$tchId] = $tchList[$tchId] + ['appUsage' => []];
                    unset($tchList[$tchId]);
//                    $tchAppUsage[$tchId] = [
//                        'tchId'     => $tchId,
//                        'tchName'   => $tchList[$tchId],
//                        'appUsage'  => []
//                    ];
                }
                $tchAppUsage[$tchId]['appUsage'][] = [
                    'appCode'       => $appCode,
                    'appName'       => $appCodeList[$appCode],
                    'taskFixNum'    => $row['taskFixNum'],
                    'taskTopicNum'  => $row['taskTopicNum'],
                    'practiceNum'   => $row['practiceNum'],
                    'lastFixTime'   => $row['lastFixTime'],
                ];
            }
        }

        //合并无数据老师
        foreach ($tchList as $tchId => $tchInfo) {
            $tchAppUsage[$tchId] = $tchInfo + [
                    'appUsage' => [[
                        'appCode'       => '',
                        'appName'       => '无数据',
                        'taskFixNum'    => '',
                        'taskTopicNum'  => '',
                        'practiceNum'   => '',
                        'lastFixTime'   => '',
                    ]]
                ];
        }
        return array_values($tchAppUsage);
        //获取2.0应用列表
//        $tchAppList2 = [];
//        $tchIds      = array_diff($tchIds, array_column($tchAppList3, 'userId'));
//        if ($tchIds) {
//            $tchGroupIds = [];
//            foreach ($tchIds as $tchId) {
//                if (!$tchList[$tchId]['groupId']) {
//                    continue;
//                }
//                $tchGroupIds[] = $tchList[$tchId]['groupId'];
//            }
//            $tchGroupIds  = array_unique($tchGroupIds);
//            $groupAppTmp  = $conn->fetchAll("SELECT ap_gr_id AS groupId, sy_name4 AS packageName, sy_name AS appName FROM app_group_power LEFT JOIN system_type ON ap_sy_id = sy_id WHERE ap_state = 0 AND sy_name1 <> 'so' AND sy_type = 'systemapplist' AND ap_gr_id IN (" . implode(',', $tchGroupIds) . ")");
//            $groupAppList = [];
//            foreach ($groupAppTmp as $row) {
//                $packageName = explode('|', $row['packageName'])[0];
//                if (isset($this->packAppCodeEnum[$packageName]) && in_array($this->packAppCodeEnum[$packageName], $this->statsAppCode)) {
//                    $groupAppList[$row['groupId']][] = [
//                        'appCode'       => $this->packAppCodeEnum[$packageName],
//                        'appName'       => $row['appName'],
//                        'packageName'   => $packageName,
//                    ];
//                }
//            }
//            foreach ($tchIds as $tchId) {
//                if (!$tchList[$tchId]['groupId']) {
//                    continue;
//                }
//                $tchAppList2[] = [
//                    'tchId'     => $tchId,
//                    'tchName'   => $tchList[$tchId]['tchName'],
//                    'appList'   => $groupAppList[$tchList[$tchId]['groupId']]
//                ];
//            }
//        }
//        die(json_encode($tchAppList2));
    }

    /**
     * 根据应用编号，教师id获取使用情况
     *
     * @param $appCode
     * @param $tchIds
     * @param $startTime
     * @param $endTime
     * @param $schoolId
     * @return array
     * @throws \Exception
     *
     * create by ck 20171103
     * modify by ck 20171106
     */
    public function getAppUsageInfo($appCode, $tchIds, $startTime, $endTime, $schoolId = null)
    {
        $config = Main::getConfigByName('stats_' . $appCode)['readDB'];
        if (!$config) {
            return [];
        }
        $config = explode('|' ,$config);
        $conn = new Mysql([
            'host'      => $config[0],
            'username'  => $config[1],
            'password'  => $config[2],
            'dbname'    => $config[3],
            'charset'   => $config[4]
        ]);
        if (!$conn) {
            throw new \Exception($appCode . '统计库连接失败！');
        }
        $tchIds   = implode(',', $tchIds);
        //刷题
        if (in_array($appCode, ['CA101001','CA101002','CA101007', 'CA101008'])) {
            $columns = 'SUM(iTaskFixNum) AS taskFixNum, SUM(iTaskAllNum) AS taskTopicNum, SUM(iSumNum) AS practiceNum';
            $sql = "SELECT iTchId as tchId,{$columns} FROM XHApp_SchoolStats WHERE iTchId IN ({$tchIds}) AND tTargetDate >= '{$startTime}' AND tTargetDate <= '{$endTime}' AND iSchoolId = '{$schoolId}' GROUP BY iTchId";
        }
        //云作业，课堂
        else if (in_array($appCode, ['CA103001','CA103001-3','CA104001'])) {
            $columns = 'SUM(iTaskRealFixNum) AS taskFixNum, SUM(iTaskRealTopicNum) AS taskTopicNum, SUM(iPracticeNum) AS practiceNum, MAX(iLastFixTime) AS lastFixTime';
            $sql = "SELECT iTchId AS tchId,{$columns} FROM (SELECT iTchId,SUM(iTaskRealFixNum) AS iTaskRealFixNum,SUM(iTaskRealTopicNum) AS iTaskRealTopicNum,SUM(iPracticeNum) AS iPracticeNum,iLastFixTime FROM XHApp_SchoolStats WHERE iTchId IN ({$tchIds}) AND tTargetDate >= '{$startTime}' AND tTargetDate <= '{$endTime}' AND iSchoolId = '{$schoolId}' GROUP BY tTargetDate,iTchId,iCoId) A GROUP BY iTchId";
      }
        else {
            $columns = 'SUM(iTaskFixNum) AS taskFixNum, SUM(iTaskAllNum) AS taskTopicNum, SUM(iPracticeNum) AS practiceNum';
            $sql = "SELECT iTchId as tchId,{$columns} FROM XHApp_SchoolStats WHERE iTchId IN ({$tchIds}) AND tTargetDate >= '{$startTime}' AND tTargetDate <= '{$endTime}' AND iSchoolId = '{$schoolId}' GROUP BY iTchId";
        }
        $tchUsage = $conn->fetchAll($sql);

        Tool::runTimestamp($tchUsage, 'lastFixTime');
        return $tchUsage;
    }

    /**
     * 获取统计应用列表
     *
     * @return array|bool|mixed|null
     *
     * create by ck 20171103
     */
    public function getStatsAppInfo()
    {
        if(Cache::exists('stats_app_list')){
            return Cache::get('stats_app_list');
        }
        $statAppList = [];

        $appStatsList = XhsysConfig::find([
            'columns'    => 'sConfigName,sConfigExplain',
            'conditions' => 'bDelete = 0 AND sSortName = "stats" AND sConfigName like "stats\_%"'
        ])->toArray();

        foreach($appStatsList as $key => $value){
            $configName = explode('_', $value['sConfigName']);
            $configName = end($configName);
            $configExplain = explode('_', $value['sConfigExplain']);
            $configExplain = end($configExplain);
//            $statAppList[end(explode('_', $value['sConfigName']))] = end(explode('_', $value['sConfigExplain']));
            $statAppList[$configName] = $configExplain;
        }
        Cache::save('stats_app_list', $statAppList);
        return $statAppList;
    }

    /**
     * 云3班级统计页面
     *
     * @return \Phalcon\Mvc\View
     *
     * create by ck 20180308
     */
    public function cloudTaskClassAction()
    {
        $this->view->pick('statsschool/cloudTaskClass');
        Assets::sweetAlert2();
        Assets::select2('js/statsschool/cloudTaskClass.js');
        return $this->view->setVars([
            'viewAll'   => School::getPower() === true,
            'schoolArr' => School::getSchools()
        ]);
    }

    /**
     * 云3班级统计详情页面
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20180308
     */
    public function cloudTaskClassDetailAction()
    {
        $this->view->pick('statsschool/cloudTaskClassDetail');
        $schoolId       = $this->request->getQuery('schoolId', 'int');
        $startTime      = $this->request->getQuery('startTime', 'string');
        $endTime        = $this->request->getQuery('endTime', 'string');
        $reverse        = $this->request->getQuery('reverse', 'string') == 'true';
        $startTime      = strtotime($startTime);
        $endTime        = strtotime($endTime . '+1 day');
        if (!$schoolId || !$startTime || !$endTime) {
            return $this->sendViewError('缺少必要参数');
        }
        if ($startTime > time()) {
            return $this->sendViewError('日期超出限制，不可查询');
        }
        if (($endTime - $startTime) > 3600 * 24 * 31) {
            return $this->sendViewError('最多查询一个月数据');
        }
        try {
            $data = $this->getCloudTaskClass($schoolId, $startTime, $endTime);

            //二维排序
            $sortClassName = $sortSubject = [];
            foreach ($data as $key => $row) {
                $sortClassName[$key] = $row['className'];
                $sortSubject[$key]   = $row['subjectName'];
                $data[$key]['taskTimeCostAvg']  = Tool::secondToTime(
                    Tool::division($row['taskTimeCost'], $row['stuNum'], 0)
                );
                $data[$key]['uploadRate']       = Tool::division($row['taskUploadNum'], $row['taskStuNum'], 2) * 100;
                $data[$key]['correctRate']      = Tool::division($row['taskCorrectNum'], $row['taskUploadNum'], 2)
                    * 100;
                $data[$key]['taskCorrectNum'] = $row['taskCorrectNum'];
                $data[$key]['taskCorrectEmendNum'] = $row['taskCorrectEmendNum'];
//                $data[$key]['correctEmendRate'] = Tool::division(
//                    $row['taskCorrectEmendNum'],
//                    $row['taskCorrectNum'],
//                    2
//                ) * 100;
            }
//            Tool::runTimeToStr($data, ['taskTimeCostAvg']);

            if (!$reverse) {
                array_multisort($sortClassName, SORT_ASC, $sortSubject, SORT_ASC, $data);
                $keyName = 'classId';
            } else {
                array_multisort($sortSubject, SORT_ASC, $sortClassName, SORT_ASC, $data);
                $keyName = 'subjectName';
            }

            $newData = [];
            foreach ($data as $key => $row) {
                $newData[$row[$keyName]][] = $row;
            }

            return $this->view->setVars([
                'data'          => $newData,
                'schoolName'    => XhschoolInfo::getSchoolSupportArray()[$schoolId],
                'reverse'       => $reverse,
            ]);
        } catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
     * 获取云3班级统计数据
     *
     * @param $schoolId
     * @param $startTime
     * @param $endTime
     * @return array|bool|mixed|\stdClass
     * @throws \Exception
     *
     * create by ck 20180308
     */
    private function getCloudTaskClass($schoolId, $startTime, $endTime)
    {
        $configName = 'CA103001-3';
        $url = Main::getConfigByName('stats_' . $configName)['url'];
        if (!$url) {
            throw new \Exception($configName . '配置地址不存在！');
        }
        $httpClient = new HttpClient($url);
        $response = $httpClient->setTimeout(60 * 5)->get('/intranet/work/statistic/school', [
            'schoolId' => $schoolId, 'startTime' => $startTime, 'endTime' => $endTime
        ]);
        if (!$response->isSuccess()) {
            throw new \Exception($configName . '请求失败：' . json_encode($response, JSON_UNESCAPED_UNICODE));
        }
        $data = $response->toArray();
        if ($data === false) {
            throw new \Exception($configName . '请求失败：返回不正确：' . $response->body);
        }

        return $data;
    }

    /**
     * 开始数据缓存
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180307
     */
    public function startCloudTaskClassCacheAction()
    {
        set_time_limit(0);
        ignore_user_abort(true);
        $schoolId = $this->request->getPost('schoolId', 'int');
        $startTime = $this->request->getPost('startTime', 'string');
        $endTime = $this->request->getPost('endTime', 'string');
        $startTime = strtotime($startTime);
        $endTime = strtotime($endTime . '+1 day');
        if (!$schoolId || !$startTime || !$endTime) {
            return $this->sendErrorResponse(400, '缺少必要参数');
        }
        if ($startTime > time()) {
            return $this->sendErrorResponse(400, '日期超出限制，不可查询');
        }
        if (($endTime - $startTime) > 3600 * 24 * 31) {
            return $this->sendErrorResponse(400, '最多查询一个月数据');
        }
        $cacheKey = "cloud_task_class_{$schoolId}_{$startTime}_{$endTime}";
        if (Cache::exists($cacheKey)) {
            return $this->sendSuccessResponse('缓存已存在，可直接使用');
        }
        try {
            $data = $this->getCloudTaskClass($schoolId, $startTime, $endTime);
            if (!Cache::save($cacheKey, $data, 3600 * 12)) {
                return $this->sendErrorResponse(500, '缓存保存失败');
            }
            return $this->sendSuccessResponse('缓存成功，可查询');
        } catch (\Exception $e) {
            Cache::save($cacheKey, '缓存失败：' . $e->getMessage(), 3600);
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 检查缓存是否存在
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180307
     */
    public function checkCloudTaskClassCacheAction()
    {
        $schoolId   = $this->request->getPost('schoolId', 'int');
        $startTime  = $this->request->getPost('startTime', 'string');
        $endTime    = $this->request->getPost('endTime', 'string');
        $startTime  = strtotime($startTime);
        $endTime = strtotime($endTime . '+1 day');
        if (!$schoolId || !$startTime || !$endTime) {
            return $this->sendErrorResponse(400, '缺少必要参数', null, false);
        }
        $cacheKey = "cloud_task_class_{$schoolId}_{$startTime}_{$endTime}";
        if (!Cache::exists($cacheKey)) {
            return $this->sendErrorResponse(500, '缓存未生成', null, false);
        }
        return $this->sendSuccessResponse('缓存存在，可查询');
    }

    /**
     * 刷题王分组统计
     *
     * @return \Phalcon\Mvc\View
     *
     * create by ck 20180322
     * modify by ck 20180418
     */
    public function brushGroupAction()
    {
        $this->view->pick('statsschool/brushGroup');
        Assets::sweetAlert2();
        Assets::select2('js/statsschool/brushGroup.js');
//        $subjectEnum = [];
//        foreach (XhsysEnum::getEnumByNodeName('学科') as $subject) {
//            $subjectEnum[$subject] = $subject;
//        }
        $subjectEnum = StatsBrushController::$brushGroupEnum['sSubject'];
        return $this->view->setVars([
            'viewAll'   => School::getPower() === true,
            'schoolArr' => User::getSchool(true),
            'subjectArr'=> $subjectEnum
        ]);
    }

    /**
     * 刷题王分组统计详情页
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20180322
     * modify by ck 20180423    添加英刷统计
     */
    public function brushGroupDetailAction()
    {
        $schoolId       = $this->request->getQuery('schoolId', 'int');
        $classId        = $this->request->getQuery('classId', 'string');
        $subject        = $this->request->getQuery('subject', 'string');
        $startTime      = $this->request->getQuery('startTime', 'string');
        $endTime        = $this->request->getQuery('endTime', 'string');
        $startTime      = strtotime($startTime);
        $endTime        = strtotime($endTime . '+1 day');
        if (!$schoolId || !$classId || !$startTime || !$endTime) {
            return $this->sendViewError('缺少必要参数');
        }
        if ($startTime > time()) {
            return $this->sendViewError('日期超出限制，不可查询');
        }
//        if (($endTime - $startTime) > 3600 * 24 * 31){
//            return $this->sendViewError('最多查询一个月数据');
//        }
        try {
            $data = $this->getBrushGroup($schoolId, $startTime, $endTime, $classId, $subject);
            if (!$data) {
                throw new \Exception('暂无数据');
            }

            //获取分组及组内学生信息
//            $studIds = array_column($data, 'userid');
            $groups = XhstatsBrushgroup::find([
                'conditions' => 'bDelete = 0 AND sClassId = :classId: AND sSubject = :subject:',
                'bind' => ['classId' => $classId, 'subject' => $subject]
            ])->toArray();
            $groups = array_column($groups, null, 'id');
            $groups = array_map(function ($group) {
                $group['mStandard'] = unserialize($group['mStandard']);
                return $group;
            }, $groups);
            $groupIds = array_keys($groups);

            //获取学生分组情况 学生id=>组id
            if ($groupIds) {
                $studGroup = XhstatsBrushgroupuser::find([
                    'columns' => 'iGroupId,iUserId',
                    'conditions' => 'bDelete = 0 AND iGroupId IN ({groupIds:array})',
                    'bind' => ['groupIds' => $groupIds]
                ])->toArray();
                $studGroup = array_column($studGroup, 'iGroupId', 'iUserId');
            } else {
                $studGroup = [];
            }

            $studs = $statusGroup = [];
            switch ($subject) {
                case '数学':
                case '科学':
                    $this->view->pick('statsschool/brushGroupDetailScience');
                    $this->dealBrushStatusForScience($statusGroup, $studs, $data, $groups, $studGroup);
                    $total = [
                        'execNum' => array_sum(array_column($studs, 'execNum')),
                        'rightNum' => array_sum(array_column($studs, 'rightNum')),
                    ];
                    $total['rightRate'] = Tool::division($total['rightNum'], $total['execNum'], 4) * 100;
                    $this->view->setVar('total', $total);
                    break;
                case '英语':
                    $this->view->pick('statsschool/brushGroupDetailEnglish');
                    $this->dealBrushStatusForEnglish($statusGroup, $studs, $data, $groups, $studGroup);
                    break;
                default:
                    throw new \Exception('科目不正确');
            }

            //学生根据分组排序
            $sortGroup = [];
            foreach ($studs as $key => $stud) {
                $sortGroup[$key] = $stud['groupName'];
            }
            array_multisort($sortGroup, SORT_ASC, $studs);

            return $this->view->setVars([
                'groups' => $groups,
                'studs' => $studs,
                'status' => $statusGroup,
                'schoolName' => XhschoolInfo::getSchoolSupportArray()[$schoolId],
            ]);
        } catch (XhException $e) {
            return $this->sendViewError($e->getMessage() . '：' . json_encode($e->getDescription(), 256));
        } catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
     * 获取刷题王分层统计
     *
     * @param $schoolId
     * @param $startTime
     * @param $endTime
     * @param $classId
     * @param $subject
     * @return mixed
     * @throws \Exception
     *
     * create by ck 20180322
     * modify by ck 20180328    更新错误提示
     * modify by ck 20180419    增加英刷接口支持
     * modify by ck 20181022    更换为大数据新接口
     */
    private function getBrushGroup($schoolId, $startTime, $endTime, $classId, $subject)
    {
        switch ($subject) {
            case '数学':
            case '科学':
                return BigData::getMathScienceBrushGroup($schoolId, $classId, $subject, $startTime, $endTime);
            case '英语':
                return BigData::getEnglishBrushGroup($schoolId, $classId, $startTime, $endTime);
            default:
                throw new \Exception('科目不正确');
        }

//        $url = Main::getConfigByName('bigData')['url'];
//        if (!$url) {
//            throw new \Exception('配置地址不存在！');
//        }
//        $httpClient = new HttpClient($url);
//        switch ($subject) {
//            case '数学':
//            case '科学':
//                $response = $httpClient->postJson('/bigdata/product_stw/getstwinfo', [
//                    'gettype'       => 'getstudent',
//                    'schoolid'      => intval($schoolId),
//                    'classid'       => intval($classId),
//                    'subjectname'   => $subject,
//                    'starttime'     => $startTime,
//                    'endedtime'     => $endTime
//                ]);
//                break;
//            case '英语':
//                $response = $httpClient->get('/bigdata/product_stw/enstwInfo/getEnStwInfo', [
//                    'schoolId'  => $schoolId,
//                    'classId'   => $classId,
//                    'startTime' => $startTime,
//                    'endTime'   => $endTime
//                ]);
//                break;
//            default:
//                throw new \Exception('科目不正确');
//        }
//        if (!$response->isSuccess()) {
//            throw new \Exception('请求失败：' . json_encode($response, JSON_UNESCAPED_UNICODE));
//        }
//        $body = $response->toArray();
//        if ($body['code'] != 200) {
//            throw new \Exception('请求失败：' . $body['msg']);
//        }
//        $data = $response->toArray()['data'];
//        if (!$data) {
//            throw new \Exception('无数据');
//        }
//        return $data;
    }

    /**
     * 处理理刷分层数据
     *
     * @param $statusGroup
     * @param $studs
     * @param $data
     * @param $groups
     * @param $studGroup
     *
     * create by ck 20180423
     * modify by ck 20181025    字段名改为驼峰
     */
    private function dealBrushStatusForScience(&$statusGroup, &$studs, $data, $groups, $studGroup)
    {
        $statusGroup = [
            'ok'    => ['explain' => '达标', 'data' => []],
            'good'  => ['explain' => '做题量大且正确率高', 'data' => []],
            'topic' => ['explain' => '做题量大，正确率接近老师要求', 'data' => []],
            'right' => ['explain' => '做题量接近老师要求，正确率高', 'data' => []],
            'bad'   => ['explain' => '未达标', 'data' => []],
        ];
        foreach ($data as $row) {
            $studId     = $row['userId'];
            $groupName  = '未分组';
            $status     = '';
            if (isset($studGroup[$studId])) {   //有分组
                $groupId   = $studGroup[$studId];
                $groupName = $groups[$groupId]['sGroupName'];
//                $standard  = unserialize($groups[$groupId]['mStandard']);
                $standard  = $groups[$groupId]['mStandard'];

                //处理是否符合条件及分组
                if ($row['topicNum'] >= $standard['topicExec'] &&
                    $row['rightRate'] >= $standard['rightRate']
                ) {
                    $status = '达标';
                    if ($row['topicNum'] >= $standard['topicExecUp'] &&
                        $row['rightRate'] >= $standard['rightRateUp']
                    ) {
                        $statusGroup['good']['data'][] = $row['userName'];
                    } else {
                        $statusGroup['ok']['data'][] = $row['userName'];
                    }
                } else {
                    $status = '未达标';
                    if ($row['topicNum'] >= $standard['topicExecUp'] &&
                        $row['rightRate'] >= $standard['rightRateDown']
                    ) {
                        $statusGroup['topic']['data'][] = $row['userName'];
                    } elseif ($row['topicNum'] >= $standard['topicExecDown'] &&
                        $row['rightRate'] >= $standard['rightRateUp']
                    ) {
                        $statusGroup['right']['data'][] = $row['userName'];
                    } else {
                        $statusGroup['bad']['data'][] = $row['userName'];
                    }
                }
            }
            $studs[] = [
                'id'        => $studId,
                'userName'  => $row['userName'],
                'execNum'   => $row['topicNum'],
                'rightRate' => $row['rightRate'],
                'rightNum'  => $row['rightNum'],
                'groupName' => $groupName,
                'status'    => $status
            ];
        }
    }

    /**
     * 处理英刷分层数据
     *
     * @param $statusGroup
     * @param $studs
     * @param $data
     * @param $groups
     * @param $studGroup
     *
     * create by ck 20180424
     * modify by ck 20180704    添加词汇应用项
     */
    private function dealBrushStatusForEnglish(&$statusGroup, &$studs, $data, $groups, $studGroup)
    {
        $statusGroup = [
            'ok'    => ['explain' => '达标', 'data' => []],
            'good'  => ['explain' => '做题量大且正确率高', 'data' => []],
            'topic' => ['explain' => '做题量大，正确率接近老师要求', 'data' => []],
            'right' => ['explain' => '做题量接近老师要求，正确率高', 'data' => []],
            'bad'   => ['explain' => '未达标', 'data' => []],
        ];
        $statusGroup = [
            'listen'    => ['explain' => '听力', 'data' => $statusGroup],
            'read'      => ['explain' => '阅读', 'data' => $statusGroup],
            'blank'     => ['explain' => '完型', 'data' => $statusGroup],
            'fillBlank' => ['explain' => '词汇应用', 'data' => $statusGroup],
        ];
        $queType    = array_keys($statusGroup);
        $queTypeNum = count($queType);
        foreach ($data as $row) {
            $studId     = $row['userId'];
            $groupName  = '未分组';
            $status     = [
                'total'     => '',
                'listen'    => '',
                'read'      => '',
                'blank'     => '',
                'fillBlank' => ''
            ];
            if (isset($studGroup[$studId])) {   //有分组
                $groupId   = $studGroup[$studId];
                $groupName = $groups[$groupId]['sGroupName'];
                $standard  = $groups[$groupId]['mStandard'];

                //处理是否符合条件及分组
                foreach ($queType as $type) {
                    if ($row[$type . 'Num'] >= $standard[$type]['topicExecUp']
                        && $row[$type . 'Rate'] >= $standard[$type]['rightRateUp']) {
                        //做题量大且正确率高
                        $target = 'good';
                        $status[$type] = '达标';
                        $row['numStats']['ok']++;
                    } elseif ($row[$type . 'Num'] >= $standard[$type]['topicExec']
                        && $row[$type . 'Rate'] >= $standard[$type]['rightRate']) {
                        //达标
                        $target = 'ok';
                        $status[$type] = '达标';
                        $row['numStats']['ok']++;
                    } elseif ($row[$type . 'Num'] >= $standard[$type]['topicExecUp']
                        && $row[$type . 'Rate'] >= $standard[$type]['rightRateDown']) {
                        //做题量大，正确率接近老师要求
                        $target = 'topic';
                        $status[$type] = '-';
                        $row['numStats']['notBad']++;
                    } elseif ($row[$type . 'Num'] >= $standard[$type]['topicExecDown']
                        && $row[$type . 'Rate'] >= $standard[$type]['rightRateUp']) {
                        //做题量接近老师要求，正确率高
                        $target = 'right';
                        $status[$type] = '-';
                        $row['numStats']['notBad']++;
                    } else {
                        //未达标
                        $target = 'bad';
                        $status[$type] = '-';
                    }
                    $statusGroup[$type]['data'][$target]['data'][] = $row['userName'];
                }
            }
            $studs[] = $row + [
                'groupName' => $groupName,
                'status'    => $status
            ];
        }

        $statusGroup['total'] = ['explain' => '总体', 'data' => [
            'ok'    => ['explain' => '达标', 'data' => []],
            'notBad'=> ['explain' => '做得较好', 'data' => []]
        ]];

        //获取各类型good及ok用户
        foreach ($studs as &$stud) {
            if (!isset($studGroup[$stud['userId']])) {
                continue;
            }
            $stud['status']['total'] = '-';
            if ($stud['numStats']['ok'] >= $queTypeNum) {
                $statusGroup['total']['data']['ok']['data'][] = $stud['userName'];
                $stud['status']['total'] = '达标';
            } elseif ($stud['numStats']['notBad'] >= 2) {
                $statusGroup['total']['data']['notBad']['data'][] = $stud['userName'];
            }
        }
        unset($stud);

        //获取各类型good及ok用户
//        $reachUser = $notBadUser = [];
//        foreach ($queType as $type) {
//            $reachUser[$type]  = array_merge($statusGroup[$type]['data']['good']['data'], $statusGroup[$type]['data']['ok']['data']);
//            $notBadUser[$type] = array_merge($reachUser[$type], $statusGroup[$type]['data']['good']['topic'], $statusGroup[$type]['data']['good']['right']);
//        }
//
//        //总体达标
//        $statusGroup['total']['data']['ok']['data'] = array_intersect($reachUser['listen'], $reachUser['read'], $reachUser['blank']);
//
//        //听力-阅读达标
//        $reach1 = array_intersect($notBadUser['listen'], $notBadUser['read']);
//        //听力-完型达标
//        $reach2 = array_intersect($notBadUser['listen'], $notBadUser['blank']);
//        //阅读-完型达标
//        $reach3 = array_intersect($notBadUser['read'], $notBadUser['blank']);
//
//        //做得较好
//        $statusGroup['total']['data']['notBad']['data'] = array_unique(array_merge($reach1, $reach2, $reach3));
    }

    /**
     * 应用数据统计
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|string
     *
     * create by ck 20180510
     */
    public function appAction()
    {
        if (!UserPower::checkUserPower('Stats_AppData')) {
            return $this->sendViewError('无查看权限');
        }
        return $this->response->redirect('/manage/statsApp/index.html');
    }

    /**
     * 学校教师教辅使用情况查询页面
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20180719
     * modify by ck 20180720
     */
    public function tchBookAction()
    {
        $this->view->pick('statsschool/tchBook');
        Assets::select2('js/statsschool/tchBook.js');
        try {
            return $this->view->setVars([
                'viewAll'   => !!School::getPower(),
                'schoolArr' => User::getSchool(true),
            ]);
        } catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
     * 学校教师教辅使用情况统计页面
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20180720
     * modify by ck 20181107    增加教师班级，科目，年级
     */
    public function tchBookInfoAction()
    {
        $this->view->pick('statsschool/tchBookInfo');
        $schoolId  = $this->request->getQuery('schoolId', 'int');
        $startTime = $this->request->getQuery('startTime', 'string');
        $endTime   = $this->request->getQuery('endTime', 'string');
        if (!$schoolId) {
            return $this->sendViewError('缺少学校id');
        }
        if (!$startTime || !$endTime) {
            return $this->sendViewError('请选择时间段查询');
        }
        try {
            $data = CloudTask::getTchBookUseInfo($schoolId, strtotime($startTime), Tool::getEndTime($endTime));

            //添加教师信息
            $tchIds = array_column($data, 'teacherId');
            if ($tchIds) {
                $tchInfo = XhsysUserTch::find([
                    'columns' => 'iUserId,sEBagClass,iCurGrade,iSubject',
                    'conditions' => 'iUserId IN ({tchIds:array})',
                    'bind' => ['tchIds' => $tchIds]
                ])->toArray();
                Tool::runEnum($tchInfo, [
                    'iCurGrade' => XhsysEnum::getEnumByNodeName('年级'),
                    'iSubject' => XhsysEnum::getEnumByNodeName('学科'),
                ]);
                $tchInfo = array_column($tchInfo, null, 'iUserId');
                foreach ($data as &$row) {
                    $tch = Tool::getValue($tchInfo, $row['teacherId'], []);
                    $row['sEBagClass'] = $tch['sEBagClass'] ?? '';
                    $row['iCurGrade'] = $tch['iCurGrade'] ?? '';
                    $row['iSubject'] = $tch['iSubject'] ?? '';
                }
                unset($row);
            }
            return $this->view->setVars([
                'data'      => $data,
                'schoolId'  => $schoolId,
                'startTime' => $startTime,
                'endTime'   => $endTime,
                'power'     => [
                    'edit' => Power::exist('Stats_BookTch_Edit')
                ]
            ]);
        } catch (XhException $e) {
            return $this->sendViewError($e->getMessage() . '：' . json_encode($e->getDescription()));
        }
    }

    /**
     * 教师单本教辅使用详情
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20180720
     */
    public function tchBookDetailAction()
    {
        $schoolId   = $this->request->getQuery('schoolId', 'int');
//        $bookId     = $this->request->getQuery('bookId', 'string');
        $teacherId  = $this->request->getQuery('teacherId', 'int');
        $startTime  = $this->request->getQuery('startTime', 'string');
        $endTime    = $this->request->getQuery('endTime', 'string');
        if (!$schoolId || !$teacherId || !$startTime || !$endTime) {
            return $this->sendViewError('缺少参数');
        }
        $this->view->pick('statsschool/tchBookDetail');
        try {
            $data = CloudTask::getTchBookUseDetail($schoolId, $teacherId, strtotime($startTime), Tool::getEndTime($endTime));
            Tool::runTimestamp($data, 'createTime');
            return $this->view->setVars([
                'data'  => $data,
                'power' => [
                    'edit' => Power::exist('Stats_BookTch_Edit')
                ]
            ]);
        } catch (XhException $e) {
            return $this->sendViewError(json_encode($e->getDescription()));
        }
    }

    /**
     * 学校增长情况
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20190109
     */
    public function risingAction()
    {
        $this->view->setTemplateBefore('listForm');
        Assets::easyUI('js/statsschool/rising.js');
        if (!Power::exist('schoolRisingStats')) {
            return $this->sendViewError('无查看权限');
        }
        $listButtonArr = $searchToolbar = [];
        $listSearchArr[] = ['type' => 'select', 'id' => 'list_status', 'data' => [0 => '-状态-', 1 => '正常', 2 => '历史']];
        $listSearchArr[] = ['type' => 'select', 'id' => 'list_province', 'style' => 'width: 150px;'];
        $listSearchArr[] = ['type' => 'select', 'id' => 'list_city', 'style' => 'width: 100px;'];
        $listSearchArr[] = ['type' => 'select', 'id' => 'list_county', 'style' => 'width: 100px;'];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_startTime', 'class' => 'easyui-datebox',
                            'label' => ' 时间： '];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_endTime', 'class' => 'easyui-datebox', 'label' => ' ~ '];
//        $listSearchArr[] = ['type' => 'text', 'id' => 'list_search', 'name' => 'list_search', 'label' => '搜索： '];
        return $this->view->setVar('List', Template::createList('list', 'Stats_SchoolRising', [
            'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
//            'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
        ]));
    }

    /**
     * 学校增长情况数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20190109
     * modify by dale 20190111  省县市 修改为名称， 修复教师为0
     */
    public function risingDataAction()
    {
        $status    = $this->request->getPost('status', 'int', 0);
        $startTime = $this->request->getPost('startTime', 'string');
        $endTime   = $this->request->getPost('endTime', 'string');
        $province  = $this->request->getPost('province', 'string');
        $city      = $this->request->getPost('city', 'string');
        $county    = $this->request->getPost('county', 'string');
        if (!$startTime || !$endTime) {
            return $this->sendErrorResponse(400, '时间为必选条件');
        }
        if ($endTime) {
            $endTime = Tool::getEndTime($endTime, false);
        }
        try {
            $conditions = [];
            if ($status && in_array($status, [1,2])) {
                $status -= 1;
                $conditions[] = "u.bHistory = {$status}";
            }
            if ($startTime) {
                $conditions[] = "u.tCreateDate >= '{$startTime}'";
            }
            if ($endTime) {
                $conditions[] = "u.tCreateDate < '{$endTime}'";
            }
            if ($county) {
                if ($county != '--区--') {
                    $conditions[] = "s.sCountyName = '{$county}'";
                }
            }
            if ($city) {
                if ($city != '--市--') {
                    $conditions[] = "s.sCityName = '{$city}'";
                }
            }
            if ($province) {
                if ($province != '--省--') {
                    $conditions[] = "s.sProvinceName = '{$province}'";
                }
            }

            //判断学校，客户扩展权限
            $schoolIds = School::getPower();
            $depIds = Power::getExtraPower('dep', 'customer');
            if ($schoolIds !== true) {
                if ($depIds === true) {
                    $schoolIds = true;
                } elseif ($depIds) {
                    $userIds = Hrm::getUserByDepId($depIds, true);
                    if ($userIds) {
                        //获取客户学校id
                        $custSchoolIds = XhcustInfo::find([
                            'columns' => 'iSchoolId',
                            'conditions' => 'iCreateUserId IN ({userIds:array}) AND bDelete = 0',
                            'bind' => ['userIds' => $userIds]
                        ])->toArray();
                        $custSchoolIds = array_filter(array_column($custSchoolIds, 'iSchoolId'));
                        if ($custSchoolIds) {
                            $schoolIds = array_values(array_merge($schoolIds, $custSchoolIds));
                        }
                    }
                }
            }
            if (!$schoolIds) {
                return $this->sendErrorResponse(403, '无扩展权限');
            }
            if ($schoolIds !== true) {
                $schoolIds = implode(',', $schoolIds);
                $conditions[] = "u.iSchoolId IN ({$schoolIds})";
            }

            //处理条件
            if ($conditions) {
                $conditions = ' AND ' . implode(' AND ', $conditions);
            } else {
                $conditions = '';
            }
            $sql = "SELECT
                    u.iSchoolId,
                    s.sSchoolName,
                    s.sProvinceName,
                    s.sCityName,
                    s.sCountyName,
                    SUM(u.iUserType = 1) AS stuNum,
                    SUM(u.iUserType = 4) AS tchNum,
                    count(DISTINCT(u.sAdClsName)) AS classNum,
                    GROUP_CONCAT(u.sAdClsName) AS classDetail
                FROM
                    XHSys_User u
                LEFT JOIN XHSchool_Info s
                ON
                    u.iSchoolId = s.iSchoolId
                WHERE
                    u.bDelete = 0
                    AND u.bDisable = 0
                    AND u.bCompany = 0
                    AND ( ( u.iUserType =1 and (LENGTH(u.sAdClsName) = LENGTH(0 + u.sAdClsName) AND LENGTH(u.sAdClsName) = 4) ) or u.iUserType = 4 )
                    AND s.iStatus IN (1,2)
                    AND u.iSchoolId NOT IN (0,1,10,1341,2747,3563,3614,3618,4160)
                    {$conditions}
                GROUP BY u.iSchoolId";
            $data = Main::runSqlPage($sql);
            foreach ($data['rows'] as &$row) {
                $row['classDetail'] = array_values(array_filter(array_unique(explode(',', $row['classDetail']))));
                $row['classNum'] = count($row['classDetail']);
                $row['classDetail'] = implode(',', $row['classDetail']);
                $row['classDetail'] = "<div title='{$row['classDetail']}'>{$row['classDetail']}</div>";
            }
            unset($row);
            $data['footer'][] = [
                'sSchoolName' => '小计：',
                'stuNum' => array_sum(array_column($data['rows'], 'stuNum')),
                'tchNum' => array_sum(array_column($data['rows'], 'tchNum')),
                'classNum' => array_sum(array_column($data['rows'], 'classNum'))
            ];
            $total = $this->db->fetchOne("SELECT
                    SUM(stuNum) AS stuNum,
                    SUM(tchNum) AS tchNum,
                    SUM(classNum) AS classNum
                FROM ({$sql}) AS a");
            $data['footer'][] = [
                'sSchoolName' => '总计：',
                'stuNum' => $total['stuNum'],
                'tchNum' => $total['tchNum'],
                'classNum' => $total['classNum']
            ];
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, '系统异常', $e->getMessage());
        }
    }
}
